package com.platform.common.utils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;

import com.platform.common.exception.BusinessException;
import com.platform.modules.sys.entity.SysUserEntity;

/**
 * Shiro工具类
 *
 * @author 肖亮
 */
public class ShiroUtils {

    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    public static SysUserEntity getUserEntityTemp(HttpServletRequest request) {
      HttpSession session=request.getSession();
      SysUserEntity user= (SysUserEntity) session.getAttribute("user");
       if(user!=null){
    	   System.out.println("用户名："+user.getUserName());
       }else{
    	   System.out.println("用户信息不存在");
       }
      return user;
    }
    
    
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    public static SysUserEntity getUserEntity() {
        return (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
    }

    public static String getUserId() {
        return getUserEntity().getUserId();
    }

    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if (kaptcha == null) {
            throw new BusinessException("验证码已失效");
        }
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }

}
